//
//  MeViewController.m
//  Ev_Master
//
//  Created by Evan on 2019/6/10.
//  Copyright © 2019 Evan. All rights reserved.
//

#import "MeViewController.h"
#import "MeCenterItemTableViewCell.h"
#import "MeBottomTableViewCell.h"
#import "WebViewController.h"
#import "UserCenter.h"
#import "MeShareQRView.h"
#import <Masonry.h>
#import "NetworkManager.h"
#import "MeOpenAccountView.h"
#import "taskSpotTrading.h"
#import "taskUserService.h"
#import "MeCardTop3TableViewCell.h"
#import "MeCenterItemCell.h"
#import "MJRefresh.h"
#import "MeBottomLogoutTableViewCell.h"

@interface MeViewController ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic,strong)    UITableView *tableView;

@end

@implementation MeViewController{
    NSArray *arrayCellIco;
    NSArray *arrayCellName;
    MeShareQRView *vv;
    MeOpenAccountView *vA;
}



- (void)viewDidLoad {
    
    [super viewDidLoad];
    self.navigationItem.title = @"会员中心";
    self.isNeedLogin = NO;
    
    
    [self initTableView];
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    vv.hidden = YES;
//    vA.hidden = YES;
    
    [self hideHeadView:YES];
    [self setHiddenTabBar:NO];
    [self setHiddenNavigation:NO];
//    [self setStatusBarBackgroundColor:[UIColor clearColor]];
    
    if ( [UserCenter shareCenter].isLogined){
        [[UserCenter shareCenter]getProfiles:^(modelUserInfo *profile) {
            [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:[NSIndexPath indexPathForRow:0 inSection:0],nil] withRowAnimation:UITableViewRowAnimationAutomatic];
            [self initShareQR];
        }];
    }
}


-(void)initTableView{
    arrayCellIco = [NSArray arrayWithObjects:@"cellIcon5",@"cellIcon6", nil ];
    arrayCellName = [NSArray arrayWithObjects: @"用户设置",@"帮助", nil ];
    
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        //进行数据刷新操作
        [[UserCenter shareCenter]refreshProfiles:^(modelUserInfo *profile) {
            [self.tableView.mj_header endRefreshing];
            [self.tableView reloadData];
        }];
    }];
    
    
    [self.tableView reloadData];
    
//    [self initAccountOpen];
    
    [self initShareQR];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshData:) name:Notification_login_ok_notice object:nil];
}

#pragma mark - refresh Data

-(void)refreshData:(id)sender{
    [self.tableView reloadData];
}

#pragma mark - Account Open
///交易所开户
-(void)initAccountOpen{
    vA = [[[NSBundle mainBundle] loadNibNamed:@"MeOpenAccountView" owner:self options:nil] objectAtIndex:0];
    [self.view addSubview:vA];
    [vA mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.view);
        make.top.equalTo(self.mas_topLayoutGuide);
        make.right.mas_equalTo(self.view);
        make.bottom.mas_equalTo(self.view).offset(-KSHeight_TabBar);
    }];
    vA.hidden = YES;
    [vA awakeFromNib];
    __weak __typeof(self)weakSelf = self;
    vA.blockNext = ^(NSInteger btnIndex) {
        WebViewController *viewController = [[WebViewController alloc]init];
        [viewController cyl_setNavigationBarHidden:NO];
        viewController.webUrl = [NSString stringWithFormat:@"%@/open-account/%ld",WebViewH5Host,btnIndex];
        [weakSelf.navigationController pushViewController:viewController animated:YES];
    };
}

#pragma mark - share QR

-(void)initShareQR{
    vv =[[[NSBundle mainBundle] loadNibNamed:@"MeShareQRView" owner:self options:nil] objectAtIndex:0];
    //    vv.frame = CGRectMake(0, KSHeight_NavBar, KScreenWidth, KScreenHeight);
    [self.view addSubview:vv];
    [vv mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.view);
        make.top.equalTo(self.mas_topLayoutGuide);
        make.right.mas_equalTo(self.view);
        make.bottom.mas_equalTo(self.view).offset(-KSHeight_TabBar);
    }];
    //生成二维码
    NSString *strQr = [NSString stringWithFormat:@"http://reg.mzmzp.cn/?referrer=%@",[UserCenter shareCenter].user.member.Mobile];
    [vv initQRdata:strQr];
}

#pragma mark - loadSigning 签到

- (void)Signing{
    [[UserCenter shareCenter] getProfiles:^(modelUserInfo *profile) {
        [DKProgressHUD showLoading];
        NSMutableDictionary *dict = [NSMutableDictionary new];
        [dict setValue:[UserCenter shareCenter].userNo forKey:@"username"];
        [taskUserService userShopSigning:dict success:^(BaseModel * _Nonnull response, BOOL success) {
            [DKProgressHUD dismiss];
            [DKProgressHUD showSuccessWithStatus:@"签到成功"];
            
        } failture:^(NSError * _Nonnull error, NSString * _Nonnull strDescription) {
            [DKProgressHUD dismiss];
            [DKProgressHUD showErrorWithStatus:strDescription];
        }];
    }];
}

#pragma mark - tableview delegate

-(UITableView *)tableView
{
    if (!_tableView) {
        
        _tableView = [[UITableView alloc]init];
        [self.view addSubview:_tableView];
        [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(self.view);
//            make.top.equalTo(self.view);
            make.top.equalTo(self.mas_topLayoutGuide);
            make.right.mas_equalTo(self.view);
            make.bottom.mas_equalTo(self.view).offset(-KSHeight_TabBar);
        }];
        
        _tableView.dataSource = self;
        _tableView.delegate = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.backgroundColor  = [UIColor clearColor];
        _tableView.scrollEnabled = YES;
        _tableView.estimatedSectionFooterHeight = 0;
        _tableView.estimatedSectionHeaderHeight = 0;
    }
    return _tableView;
}


#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return arrayCellIco.count + 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return 1;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        return 228;
    }else if (indexPath.section == 1) {
        return 350;
    }
    return 70;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.section == 0) {
        MeCardTop3TableViewCell *cell = [MeCardTop3TableViewCell cellWithTableView:tableView IndexPath:indexPath];
        
        NSString *strName = @"注册或登录";
        NSString *strDl = @"";
        NSString *str1 = @"0";
        NSString *str2 = @"0";
        NSString *str3 = @"0";
        if ( [UserCenter shareCenter].isLogined){
            
            strName = [UserCenter shareCenter].user.member.username;
            strDl = [self GetUserLevelName: [UserCenter shareCenter].user.member.UserLevel];
            str1 = [UserCenter shareCenter].user.member.AddupBonus1;
            str2 = [UserCenter shareCenter].user.member.SonWallet;
            str3 = [UserCenter shareCenter].user.member.Wallet;
            cell.labelSh.text = [self GetAgentLevelName:[UserCenter shareCenter].user.member.AgentLevel];
        }
        cell.labelName.text =  [UserCenter shareCenter].user.member.pid;
        cell.labelDaili.text = strName;
        cell.walletGG.text = str1;
        cell.labeldDT.text = str2;
        cell.labelJT.text = str3;
        
        cell.blockBtnSigningClick = ^{
            [self Signing];
        };
        
        return cell;
    }
    else if(indexPath.section == 1){
        MeCenterItemCell *cell = [MeCenterItemCell cellWithTableView:tableView IndexPath:indexPath];
        cell.blockBtnClick = ^(NSInteger btnIndex) {
            [self cellCenterNavi:btnIndex];
        };
        return cell;
    }
    
    MeBottomLogoutTableViewCell *cell = [MeBottomLogoutTableViewCell cellWithTableView:tableView IndexPath:indexPath];
    cell.blockBtnLogoutClick = ^{
        [[UserCenter shareCenter]logout:^(BOOL suc, NSString *error) {
            LoginNavigationController *login = [[LoginNavigationController alloc]init];
            [self presentViewController:login animated:YES completion:nil];
        }];
    };
    
    return cell ;
//    MeBottomTableViewCell *cell = [MeBottomTableViewCell cellWithTableView:tableView IndexPath:indexPath];
//    NSInteger index = (indexPath.section -2);
//    cell.cellIco.image = [UIImage imageNamed:[arrayCellIco objectAtIndex:index]];
//    cell.cellTitle.text = [arrayCellName objectAtIndex:index];
//
//    return cell;
    
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    WebViewController* viewController = [[WebViewController alloc]init];
    [viewController cyl_setNavigationBarHidden:NO];
    [viewController viewDidLayoutSubviews];
    
    self.isNeedLogin = YES;
    [[UserCenter shareCenter] getProfiles:^(modelUserInfo *profile) {
        
        if(indexPath.section <1)
            return;
        switch (indexPath.section) {
                
            case 2:
                viewController.webUrl = [NSString stringWithFormat:@"%@/user/settings",WebViewH5Host];
                break;
            case 3:
                viewController.webUrl = [NSString stringWithFormat:@"%@/user/help",WebViewH5Host];
                break;
            default:
                break;
        }
        if(viewController.webUrl !=nil){
            
            [self.navigationController  pushViewController:viewController animated:YES];
        }
    }];
    
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

#pragma mark - 中间按钮组点击事件

-(void)cellCenterNavi:(NSInteger)btnIndex{
    [DKProgressHUD showLoading];
    self.view.userInteractionEnabled = NO;
    self.isNeedLogin = YES;
    [[UserCenter shareCenter] getProfiles:^(modelUserInfo *profile) {
        self.view.userInteractionEnabled = YES;
        [DKProgressHUD dismiss];
        NSString *strUrl = @"";
        switch (btnIndex) {
            case 1://新手指南
            {
                strUrl = @"/user/guide";
                break;
            }
                break;
            case 2://我的推广
                strUrl = @"/user/arrange";
                break;
            case 3://分享推广
                 self->vv.hidden = NO;
                break;
            case 4://实名认证
            {
                if (([[UserCenter shareCenter].user.member.AgentLevel integerValue]) >= 1) {
                    [DKProgressHUD showErrorWithStatus:@"当前用户已实名"];
                    return ;
                }
                strUrl = @"/user/authenticat";
            }
                break;
            case 5://收款管理
            {
                strUrl = @"/user/Administration";
                break;
            }
                break;
            case 6://常见问题
                strUrl = @"/user/problem";
                break;
            case 7://系统公告
                 strUrl = @"/user/help/news";
                break;
            case 8://安全中心
                strUrl = @"/user/settings";
                break;
            case 9://关于我们
                strUrl = @"/user/help/";
                break;
        }
        if(strUrl.length>0)
        {
            WebViewController *viewController = [[WebViewController alloc]init];
            [viewController cyl_setNavigationBarHidden:NO];
            viewController.webUrl = [NSString stringWithFormat:@"%@%@",WebViewH5Host,strUrl];
            [self.navigationController  pushViewController:viewController animated:YES];
        }
    }];
}


-(void)postBankMsg:(NSInteger)btnIndex{
    [DKProgressHUD showLoading];
    NSMutableDictionary *dict = [NSMutableDictionary new];
    [dict setValue:[UserCenter shareCenter].userNo forKey:@"username"];
    [taskSpotTrading getManageSpotTrading:dict success:^(SpotTradingData * _Nonnull response, BOOL success) {
        [DKProgressHUD dismiss];
        if ([[[[[response.data valueForKey:@"MEBS_MOBILE"] valueForKey:@"REP"] valueForKey:@"RESULTLIST"] valueForKey:@"US_OP"]  isEqualToString:@"0"] || ![[UserCenter shareCenter].user.member.AgentLevel  isEqualToString: @"5"]) {
            self->vA.hidden = NO;
        }else{
            [DKProgressHUD showInfoWithStatus:@"已开户注册成功"];
            return;
        }
    } failture:^(NSError * _Nonnull error, NSString * _Nonnull strDescription) {
        [DKProgressHUD dismiss];
        [DKProgressHUD showErrorWithStatus:strDescription];
    }];
}

#pragma mark - AgentLevel 字典

-(NSString *)GetAgentLevelName:(NSString*)insLevel{
    NSInteger inl = [insLevel integerValue];
    switch (inl) {
        case 0:
            return  @"未实名";
        case 1:
            return  @"已实名";
        case 2:
            return  @"已实名";
        case 3:
            return  @"已开户";
        case 5:
            return  @"已签约";
        default:
            return @"未知";
            break;
    }
    
}

#pragma mark - userLevel 字典

-(NSString *)GetUserLevelName:(NSString*)insLevel{
    NSInteger inl = [insLevel integerValue];
    switch (inl) {
        case 0:
            return @"普通用户";
        case 2:
            return @"社区商";
        case 3:
            return @"县代";
        case 4:
            return @"市代";
        case 5:
            return @"省代";
        case 6:
            return @"总代";
        default:
            return @"未知";
    }
}

@end
